package top.shmly.universal.utils.impl;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Clock;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.DefaultClock;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import top.shmly.universal.base.common.SysUser;
import top.shmly.universal.base.constant.JWTConstants;
import top.shmly.universal.config.security.AuthUser;
import top.shmly.universal.utils.JwtUtils;

import java.util.*;
import java.util.function.Function;

/**
 * @program: universal
 * @description: JWT工具类
 * @author: Jibny
 * @date 2021-04-25 10:34:07
 */
public class JwtUtilsImpl implements JwtUtils {

    private static final String secret = "X-Access-Token";

    private static final Long expiration = JWTConstants.EXPIRATION;

    private static final String tokenHeader = JWTConstants.TOKEN_HEADER;


    private final Clock clock = DefaultClock.INSTANCE;


    @Override
    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        return doGenerateToken(claims, userDetails.getUsername());
    }

    @Override
    public String doGenerateToken(Map<String, Object> claims, String subject) {
        final Date createdDate = clock.now();
        final Date expirationDate = calculateExpirationDate(createdDate);

        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(createdDate)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    @Override
    public Date calculateExpirationDate(Date createdDate) {
        return new Date(createdDate.getTime() + expiration);
    }

    @Override
    public Boolean validateToken(String token, UserDetails userDetails) {
        AuthUser user = (AuthUser) userDetails;
        final String username = getUsernameFromToken(token);
        return (username.equals(user.getUsername())
                && !isTokenExpired(token)
        );
    }

    @Override
    public String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }

    @Override
    public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    @Override
    public Claims getAllClaimsFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    @Override
    public Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(clock.now());
    }

    @Override
    public Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

    public static void main(String[] args) {
        Set<SimpleGrantedAuthority> grantedAuthorities = new HashSet<>();
        AuthUser user = new AuthUser("username"
                , "123456", grantedAuthorities);
        JwtUtils jwtUtils = JwtUtilsImpl.getInstance();
        String token = jwtUtils.generateToken(user);
        System.out.println("测试用户的ToKen：" + token);
        System.out.println("测试ToKen当前用户：" + jwtUtils.getUsernameFromToken(token));
        System.out.println(jwtUtils.getClaimFromToken(token, Claims::getSubject));
    }


    private static class SingletonHolder {
        private static final JwtUtilsImpl singletonInstance = new JwtUtilsImpl();
    }


    private JwtUtilsImpl() {
    }

    public static JwtUtilsImpl getInstance() {
        return JwtUtilsImpl.SingletonHolder.singletonInstance;
    }
}
